package com.zg.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zg.pojo.Template;
import com.zg.service.TemplateService;

@Controller
@RequestMapping("/template")
public class TemplateController {
	@Resource
	private TemplateService templateService;
	
	@RequestMapping(value="/addtemplate", method=RequestMethod.GET)
	public String addTemplateForm(HttpServletRequest request, Model model) {
		return "template/addTemplate";
	}
	
	@RequestMapping(value="/addtemplate", method=RequestMethod.POST)
	public String addTemplate(HttpServletRequest request, Model model){
		String name=new String(request.getParameter("name"));
		String description=new String(request.getParameter("description"));
		
		Template template = new Template();
		
		template.setName(name);
		template.setDescription(description);
		
		return "redirect:/template/listtemplate";
	}

	@RequestMapping(value="/listtemplate")
	public String listTemplate(HttpServletRequest request,Model model) {
		List<Template> templates;
		templates = this.templateService.getAll();
		model.addAttribute("list", templates);
		return "template/listTemplate";
	}
	
	@RequestMapping(value="/edittemplate", method=RequestMethod.GET)
	public String editTemplateForm(HttpServletRequest request,Model model){
		Template template = new Template();
		int id = new Integer(request.getParameter("id"));
		template = this.templateService.getTemplateById(id);
		
		model.addAttribute("template", template);
		
		return "template/editTemplate";
	}
	
	@RequestMapping(value="/edittemplate", method=RequestMethod.POST)
	public String editTemplate(HttpServletRequest request,Model model){
		int id = new Integer(request.getParameter("id"));
		String name = new String(request.getParameter("name"));
		String description = new String(request.getParameter("description"));
		Template template = new Template();
		template = this.templateService.getTemplateById(id);
		
		template.setName(name);
		template.setDescription(description);
		
		this.templateService.updateByParimaryKeySelective(template);
		return "redirect:/template/listtemplate";
	}
}
	
